package com.cby.library.tool.log

import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.cby.library.tool.R
import com.cby.library.tool.crash.ui.CrashDetailsActivity
import com.cby.library.tool.crash.ui.listener.OnItemClickListener
import com.cby.library.tool.util.FileUtils
import java.io.File
import java.lang.Exception
import java.util.*

/**
 * @description: CbyLogInfoListActivity
 *
 * @author ChenBaoyang
 * @date 2021/10/22 17:01
 */
class CbyLogInfoListActivity : Activity(), View.OnClickListener {
    private var mLlBack: LinearLayout? = null
    private var mTvDelete: TextView? = null
    private var mSwipeRefreshLayout: SwipeRefreshLayout? = null
    private var mRecycleView: RecyclerView? = null
    private var fileList: List<File>? = null
    private val handler = Handler()
    private var cbyLogInfoAdapter: CbyLogInfoAdapter? = null
    private var progressDialog: ProgressDialog? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_log_info_list)
        initFindViewById()
        initViews()
        initRefreshView()
        initListener()
    }

    private fun initFindViewById() {
        mLlBack = findViewById(R.id.ll_back)
        mTvDelete = findViewById(R.id.tv_delete)
        mSwipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)
        mRecycleView = findViewById(R.id.recycleView)
    }

    private fun initViews() {
        mRecycleView!!.itemAnimator = DefaultItemAnimator()
        val linearLayoutManager = LinearLayoutManager(
            this, LinearLayoutManager.VERTICAL, false
        )
        mRecycleView!!.layoutManager = linearLayoutManager
    }


    private fun initListener() {
        mLlBack!!.setOnClickListener(this)
        mTvDelete!!.setOnClickListener(this)
    }


    private fun initRefreshView() {
        //设置刷新球颜色
        mSwipeRefreshLayout!!.setColorSchemeColors(
            Color.BLACK,
            Color.YELLOW,
            Color.RED,
            Color.GREEN
        )
        mSwipeRefreshLayout!!.setOnRefreshListener {
            if (!mSwipeRefreshLayout!!.isRefreshing) {
                initCrashFileList()
            }
        }
        mSwipeRefreshLayout!!.post {
            mSwipeRefreshLayout!!.isRefreshing = true
            initCrashFileList()
        }
    }


    private fun initCrashFileList() {
        //获取日志
        Thread { getCrashList() }.start()
    }

    private fun getCrashList() {
        //重新获取
        fileList = FileUtils.getLogFileList(this)
        //排序
        Collections.sort(fileList) { file01, file02 ->
            try {
                //根据修改时间排序
                val lastModified01 = file01.lastModified()
                val lastModified02 = file02.lastModified()
                if (lastModified01 > lastModified02) {
                    -1
                } else {
                    1
                }
            } catch (e: Exception) {
                1
            }
        }

        //通知页面刷新
        handler.post {
            if (progressDialog != null && progressDialog!!.isShowing) {
                progressDialog!!.hide()
            }
            initAdapter()
        }
    }


    private fun initAdapter() {
        if (cbyLogInfoAdapter == null) {
            cbyLogInfoAdapter = CbyLogInfoAdapter(this, fileList)
            mRecycleView!!.adapter = cbyLogInfoAdapter
            cbyLogInfoAdapter!!.setOnItemClickLitener(object : OnItemClickListener {
                override fun onItemClick(view: View, position: Int) {
                    if (fileList!!.size > position && position >= 0) {
                        val intent =
                            Intent(this@CbyLogInfoListActivity, CbyLogDetailsActivity::class.java)
                        val file = fileList!![position]
                        intent.putExtra(CbyLogDetailsActivity.INTENT_KEY_FILE_PATH,
                            file.absolutePath
                        )
                        startActivity(intent)
                    }
                }

                override fun onLongClick(view: View, position: Int) {
                    if (fileList!!.size > position && position >= 0) {
                        //弹出Dialog是否删除当前
                        val builder = AlertDialog.Builder(this@CbyLogInfoListActivity)
                        builder.setTitle("提示")
                        builder.setMessage("是否删除当前日志?")
                        builder.setNegativeButton("取消", null)
                        builder.setPositiveButton(
                            "删除"
                        ) { _, i ->
                            progressDialog =
                                ProgressDialog.show(this@CbyLogInfoListActivity, "提示", "正在删除...")
                            progressDialog?.show()
                            //删除单个
                            Thread {
                                val file = fileList!![position]
                                FileUtils.deleteFile(file.path)
                                //重新获取
                                getCrashList()
                            }.start()
                        }
                        builder.show()
                    }
                }
            })
        } else {
            cbyLogInfoAdapter!!.updateDatas(fileList)
        }
        mSwipeRefreshLayout!!.isRefreshing = false
    }


    override fun onClick(v: View) {
        val i = v.id
        when (i) {
            R.id.tv_delete -> {
                deleteAll()
            }
            R.id.ll_back -> {
                finish()
            }
        }
    }

    private fun deleteAll() {
        //弹出Dialog是否删除全部
        val builder = AlertDialog.Builder(this)
        builder.setTitle("提示")
        builder.setMessage("是否删除全部日志?")
        builder.setNegativeButton("取消", null)
        builder.setPositiveButton(
            "删除"
        ) { dialogInterface, i ->
            progressDialog = ProgressDialog.show(
                this@CbyLogInfoListActivity, "提示", "正在删除..."
            )
            progressDialog?.show()

            //删除全部
            Thread {
                val fileCrash =
                    File(FileUtils.getLogPath(this@CbyLogInfoListActivity))
                FileUtils.deleteAllFiles(fileCrash)
                //重新获取
                getCrashList()
            }.start()
        }
        builder.show()
    }
}